﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NmbpProject2.BusinessLayer;
using NmbpProject2.DboClasses;

namespace NmbpProject2.PresentationLayer
{
    public partial class CompApplicationForm : Form
    {
        public CompApplicationForm()
        {
            InitializeComponent();
            // prepare dataGridView
            refreshDataSource();
            foreach (DataGridViewColumn column in dataGridViewCompApplications.Columns)
            {
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            }
            dataGridViewCompApplications.Columns["LanguagesString"].HeaderText = "Prog. languages";
            dataGridViewCompApplications.Columns["CategoriesString"].HeaderText = "Categories";
            // prepare dropDowns
            PersonBL pBL = new PersonBL();
            cmbAddPerson.DataSource = pBL.getAllPeople();
            cmbEditPerson.DataSource = pBL.getAllPeople();
            CompetitionBL cpBL = new CompetitionBL();
            List<Competition> allCompetitions = cpBL.allCompetitions("");
            cmbAddCompetition.DataSource = allCompetitions;
            cmbEditCompetition.DataSource = allCompetitions;
            // prepare checkBoxFields
            CategoryBL catBL = new CategoryBL();
            List<Category> allCategories = catBL.getAllCategories();
            foreach (Category category in allCategories)
            {
                chklAddCategories.Items.Add(category, CheckState.Unchecked);
                chklEditCategories.Items.Add(category, CheckState.Unchecked);
            }
            ProgLanguageBL progBL = new ProgLanguageBL();
            List<ProgLanguage> allLanguages = progBL.getAllLangs();
            if (allLanguages != null)
                foreach (ProgLanguage language in allLanguages)
                {
                    chklAddProgLanguages.Items.Add(language, CheckState.Unchecked);
                    chklEditProgLanguages.Items.Add(language, CheckState.Unchecked);
                }
        }

        /// <summary>
        /// Dohvaća popis svih ljudi. Listu svih ljudi povezuje
        /// kao izvor podataka za dataGridView na formi.
        /// </summary>
        private void refreshDataSource()
        {
            CompApplicationBL cBL = new CompApplicationBL();
            List<CompApplication> allApplications = cBL.getAllApplications();
            dataGridViewCompApplications.DataSource = allApplications;
            dataGridViewCompApplications.Refresh();
        }

        private void buttonAddCompApplication_Click(object sender, EventArgs e)
        {
            Person person = (Person)cmbAddPerson.SelectedItem;
            DateTime date = dtAddDate.Value;
            CheckedListBox.CheckedItemCollection col = chklAddProgLanguages.CheckedItems;
            List<ProgLanguage> progLanguages = new List<ProgLanguage>();
            foreach (object checkedItem in col)
            {
                progLanguages.Add((ProgLanguage)checkedItem);
            }
            col = chklAddCategories.CheckedItems;
            List<Category> categories = new List<Category>();
            foreach (object checkedItem in col)
            {
                categories.Add((Category)checkedItem);
            }
            Competition competition = (Competition)cmbAddCompetition.SelectedItem;
            if (validateInput(null, person, date, categories, progLanguages, competition))
            {
                CompApplicationBL cBL = new CompApplicationBL();
                cBL.insertApplication(person, progLanguages, date, categories, competition);
                refreshDataSource();
            }
        }

        private void buttonEditCompApplication_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectedRows = dataGridViewCompApplications.SelectedRows;
            if (selectedRows.Count == 1)
            {
                Person person = (Person)cmbEditPerson.SelectedItem;
                DateTime date = dtEditDate.Value;
                CheckedListBox.CheckedItemCollection col = chklEditProgLanguages.CheckedItems;
                List<ProgLanguage> progLanguages = new List<ProgLanguage>();
                foreach (object checkedItem in col)
                {
                    progLanguages.Add((ProgLanguage)checkedItem);
                }
                col = chklEditCategories.CheckedItems;
                List<Category> categories = new List<Category>();
                foreach (object checkedItem in col)
                {
                    categories.Add((Category)checkedItem);
                }
                Competition competition = (Competition)cmbEditCompetition.SelectedItem;
                CompApplication application = (CompApplication)selectedRows[0].DataBoundItem;
                if (validateInput(application, person, date, categories, progLanguages, competition))
                {
                    CompApplicationBL cBL = new CompApplicationBL();
                    cBL.update(application, person, progLanguages, date, categories, competition);
                    refreshDataSource();
                }
            }
        }

        private void buttonDeleteCompApplication_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectedRows = dataGridViewCompApplications.SelectedRows;
            if (selectedRows.Count > 0)
            {
                List<CompApplication> applications = new List<CompApplication>();
                CompApplicationBL cBL = new CompApplicationBL();
                for (int i = 0; i < selectedRows.Count; i++)
                {
                    applications.Add((CompApplication)selectedRows[i].DataBoundItem);
                }
                if (MessageBox.Show(
                        "Are you sure you want to delete selected applications?",
                        "Confirm delete",
                        MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    cBL.delete(applications);
                }
                refreshDataSource();
            }
        }

        private bool validateInput(CompApplication application, Person person, DateTime date, List<Category> categories,
                                   List<ProgLanguage> languages, Competition competition)
        {
            bool valid = true;
            try
            {
                CompApplicationBL cBL = new CompApplicationBL();
                if (cBL.exists(application, person, competition))
                {
                    valid = false;
                    throw new Exception("There exists already an application for this person in this competition!");
                }
                if (competition.Date < date)
                {
                    valid = false;
                    throw new Exception("Date cannot be later than the competition date!");
                }
                if (categories.Count == 0)
                {
                    valid = false;
                    throw new Exception("At least one category must be selected!");
                }
                if (languages.Count == 0)
                {
                    valid = false;
                    throw new Exception("At least one programming language must be selected!");
                }
                // Supported languages
                foreach (ProgLanguage aLanguage in languages)
                {
                    bool langValid = false;
                    foreach (ProgLanguage cLanguage in competition.ProgLanguages)
                    {
                        if (aLanguage == cLanguage)
                        {
                            langValid = true;
                            break;
                        }
                        langValid = false;
                    }
                    if (!langValid)
                    {
                        valid = false;
                        string message = "Chose from: ";
                        foreach (ProgLanguage language in competition.ProgLanguages)
                        {
                            message = String.Concat(message, "\n'", language.Name, "'");
                        }
                        message = String.Concat("Programming language(s) are not supported by the competition! ",
                                                message);
                        throw new Exception(message);
                    }
                }

                // Supported categories
                foreach (Category aCategory in categories)
                {
                    bool catValid = false;
                    foreach (Category cCategory in competition.Categories)
                    {
                        if (aCategory == cCategory)
                        {
                            catValid = true;
                            break;
                        }
                        catValid = false;
                    }
                    if (!catValid)
                    {
                        valid = false;
                        string message = "Chose from: ";
                        foreach (Category category in competition.Categories)
                        {
                            message = String.Concat(message, "\n'", category.Name, "'");
                        }
                        message = String.Concat("Category(s) are not supported by the competition! ", message);
                        throw new Exception(message);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return valid;
        }

        private void dataGridViewCompApplications_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectedRows = dataGridViewCompApplications.SelectedRows;
            if (selectedRows.Count == 1)
            {
                CompApplication application = (CompApplication)selectedRows[0].DataBoundItem;
                // Set comboBoxes
                cmbEditPerson.SelectedItem = application.Person;
                dtEditDate.Value = application.Date;
                cmbEditCompetition.SelectedItem = application.Competition;
                // Clear checkboxes
                for (int i = 0; i < chklEditCategories.Items.Count; i++)
                {
                    chklEditCategories.SetItemChecked(i, false);
                }
                for (int i = 0; i < chklEditProgLanguages.Items.Count; i++)
                {
                    chklEditProgLanguages.SetItemChecked(i, false);
                }
                // Check boxes
                if (application.Categories != null)
                    foreach (Category category in application.Categories)
                    {
                        for (int i = 0; i < chklEditCategories.Items.Count; i++)
                        {
                            if (chklEditCategories.Items[i] == category)
                            {
                                chklEditCategories.SetItemChecked(i, true);
                                break;
                            }
                        }
                    }
                if (application.ProgLanguages != null)
                    foreach (ProgLanguage language in application.ProgLanguages)
                    {
                        for (int i = 0; i < chklEditProgLanguages.Items.Count; i++)
                        {
                            if (chklEditProgLanguages.Items[i] == language)
                            {
                                chklEditProgLanguages.SetItemChecked(i, true);
                                break;
                            }
                        }
                    }
            }
            else
            {
                cmbEditPerson.SelectedIndex = 0;
                cmbEditCompetition.SelectedIndex = 0;
                dtEditDate.Value = DateTime.Today;
                // Clear checkboxes
                for (int i = 0; i < chklEditCategories.Items.Count; i++)
                {
                    chklEditCategories.SetItemChecked(i, false);
                }
            }
        }

        private void dataGridViewCompApplications_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
       
    }
}